<?php
declare(strict_types=1);

namespace App\Controller\Chat\Ws;

use App\Constants\Chat\Chat;
use App\Controller\AbstractController;
use App\Foundation\Facades\MessageParser;
use App\Model\Auth\User;
use App\Model\Chat\ChatHistory;
use App\Model\Chat\Group;
use App\Service\Auth\UserService;
use App\Service\Chat\ChatService;
use App\Service\SenderService;
use App\Task\Laboratory\FriendWsTask;
use App\Task\Laboratory\GroupWsTask;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\WebSocketServer\Context;


/**
 * 消息控制器
 * Class MessageController
 * @package App\Controller\Chat\Ws
 * @Controller(prefix="message",server="ws")
 */
class MessageController extends AbstractController
{


    /**
     * 发送消息
     * @RequestMapping(path="msg",methods="POST")
     */
    public function msg()
    {
        $user_info = Context::get('user_info');
        $msg = Context::get('msg');
        $fd = Context::get('fd');
        $chat_id = $msg['chat_id'] ?? '';
        if (!$chat_id) {
            $this->throwExp('参数错误');
        }
        $chat_service = ChatService::getInstance();
        try {
            $chat_list = $chat_service->getChatList($chat_id, $user_info['id']);
        } catch (\Throwable $throwable) {
            SenderService::getInstance()->debug($fd, $throwable->getMessage());
            return [];
        }
        //创建聊天记录
        $chat_obj = ChatHistory::create([
            'chat_id' => $chat_id,
            'user_id' => $user_info['id'],
            'type' => Chat::CHAT_TYPE_USER,
            'msg_type' => $msg['type'],
            'content' => json_encode($msg['content']),
            'create_at' => time(),
        ]);
        return $this->getSendList($chat_list, $chat_obj);
    }

    protected function getSendList($chat_list, $chat_obj)
    {
        /** 这里通知其他对象 */
        $chat_id=$chat_list['chat_id'];
        $user_state = UserService::getInstance()->getByUid($chat_obj['user_id']);
        $face = $user_state['avatar']??'';
        $list = [];
        $user_ids = explode(',', $chat_list['user_ids']);
        foreach ($user_ids as $user_id) {
            if ($chat_obj['user_id'] != $user_id) {
                $friend_chat_list = ChatService::getInstance()->getUserChatList($chat_id, $user_id);
                if (!empty($friend_chat_list)) {
                    $friend_chat_list['not_read_num'] += 1;
                    ChatService::saveChatList($friend_chat_list);
                }
            }
            /** 发送通知 */
            $fd = ChatService::isOnline($user_id);
            if (!$fd) {
                continue;
            }
            $list = [
                'fd' => $fd,
                'cmd' => 'chat',
                'payload' => [
                    'chat_id' => $chat_id,
                    'type' => $chat_obj['msg_type'],
                    'content' => [
                        'id' => $chat_obj->id,
                        'type' => $chat_obj['msg_type'],
                        'time' => time(),
                        'user_info' => [
                            'user_id' => $chat_obj['user_id'],
                            'name' => $user_state ? $user_state->nickname : '',
                            'face' => $face,
                        ],
                        'content' => $chat_obj['content'],
                    ],
                ]
            ];
        }
        return $list;
    }

    /**
     * 合并转发信息
     * @RequestMapping(path="merge_forward_message",methods="POST")
     */
    public function mergeForwardMessage()
    {
        $chatMessage = MessageParser::decode(context_get('chat_message'));
        $contactData = $chatMessage['message'];

        $content = json_encode($contactData['message']);
        $user = $contactData['user'];
        foreach ($contactData['contact'] as $item) {
            if ($item['is_group'] == 1) {
                $groupInfo = Group::query()->where('group_id', $item['id'])->first();
                if (empty($groupInfo)) continue;
                $groupInfo = objToArray($groupInfo);
                $this->container->get(GroupWsTask::class)->mergeForwardMessage($groupInfo, $user, $content);
            } else {
                $userInfo = User::query()->where('id', $item['id'])->first();
                if (empty($userInfo)) continue;
                $userInfo = objToArray($userInfo);
                $this->container->get(FriendWsTask::class)->mergeForwardMessage($userInfo, $user, $content);
            }
        }
    }

    /**
     * 转发信息
     * @RequestMapping(path="forward_message",methods="POST")
     */
    public function forwardMessage()
    {
        $chatMessage = MessageParser::decode(context_get('chat_message'));
        $contactData = $chatMessage['message'];

        $user = $contactData['user'];
        foreach ($contactData['contact'] as $item) {
            if ($item['is_group'] == 1) {
                $groupInfo = Group::query()->where('group_id', $item['id'])->first();
                if (empty($groupInfo)) continue;
                $groupInfo = objToArray($groupInfo);
                $this->container->get(GroupWsTask::class)->forwardMessage($groupInfo, $user, $contactData['message']);
            } else {
                $userInfo = User::query()->where('id', $item['id'])->first();
                if (empty($userInfo)) continue;
                $userInfo = objToArray($userInfo);
                $this->container->get(FriendWsTask::class)->forwardMessage($userInfo, $user, $contactData['message']);
            }
        }
    }
}

